<template>
  <div>
    <NavigationComponent />
    <br />
    <div class="course-schedule">
      <h2>请选择日期和时间</h2>
      <input type="datetime-local" v-model="selectedDateTime" @change="handleDateTimeChange" />
      <div v-if="filteredCourses.length">
        <h3>{{ dayTitle }}</h3>
        <ul>
          <li v-for="(course, index) in filteredCourses" :key="index" @click="navigateToStudentsList(course)">
            {{ course.className }} - {{ course.teacherName || "无教师信息" }}
          </li>
        </ul>
      </div>
      <div v-else>
        <h3>{{ dayTitle }}</h3>
        <h4>该日期没有课程安排</h4>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mapActions, mapState } from "vuex";
import NavigationComponent from "./NavigationComponent.vue";
import "@/assets/SelectClass.css";

export default {
  name: "SelectClass",
  components: {
    NavigationComponent,
  },
  data() {
    return {
      courses: {}, // 课程数据
      filteredCourses: [], // 过滤后的课程数据
      selectedDateTime: '', // 选定的日期和时间
      selectedTimeSlot: undefined, // 当前处理的时间段
    };
  },
  computed: {
    ...mapState(["selectedTime", "selectedClass"]),  // 映射 selectedClass
    dayTitle() {
      if (!this.selectedTimeSlot) return '';
      const dayNum_mapTo_dayEng = {
        "0": "Sunday",
        "1": "Monday",
        "2": "Tuesday",
        "3": "Wednesday",
        "4": "Thursday",
        "5": "Friday",
        "6": "Saturday"
      };
      const selectedDay = dayNum_mapTo_dayEng[String(this.selectedTimeSlot.getDay())];
      return `${selectedDay} ${this.formatDate(this.selectedTimeSlot)}`;
    }
  },
  watch: {
    selectedTime(newTime) {
      this.selectedTimeSlot = new Date(newTime); // Vuex 状态变化-->更新本地数据
      this.filterCourses();
    },
  },
  methods: {
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，因此要加1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleDateTimeChange() {
      this.selectedTimeSlot = new Date(this.selectedDateTime);
      this.filterCourses();
      this.updateSelectedTime(this.selectedDateTime); // 更新 Vuex 状态
    },
    ...mapActions(["updateSelectedTime", "updateSelectedClass"]), // 将 Vuex actions 映射为组件方法
    filterCourses() {
      if (!this.selectedTimeSlot) {
        this.selectedTimeSlot = new Date();
      }

      const dayNum_mapTo_dayEng = {
        "0": "sunday",
        "1": "monday",
        "2": "tuesday",
        "3": "wednesday",
        "4": "thursday",
        "5": "friday",
        "6": "saturday"
      };

      const classNum_mapTo_time = {
        "1-2": ["08:40", "10:00"],
        "3-4": ["10:10", "11:40"],
        "5-6": ["13:30", "15:00"],
        "7-8": ["15:10", "16:40"]
      };

      const selectedDay = dayNum_mapTo_dayEng[String(this.selectedTimeSlot.getDay())];

      this.filteredCourses = []; // 清空之前的过滤结果
      for (const key in this.courses) {
        if (key === selectedDay) {
          for (const item of this.courses[key]) {
            for (const classNum in classNum_mapTo_time) {
              if (item[classNum] && this.IsInWeekdayTime(this.selectedTimeSlot, classNum, classNum_mapTo_time)) {
                this.filteredCourses.push(item);
                // 更新 selectedClass 状态
                this.updateSelectedClass(item.className);
                break; // 只需要匹配一个时间段
              }
            }
          }
        }
      }
    },
    IsInWeekdayTime(date, classNum, classNum_mapTo_time) {
      const [startTime, endTime] = classNum_mapTo_time[classNum];
      const [startHours, startMinutes] = startTime.split(':').map(Number);
      const [endHours, endMinutes] = endTime.split(':').map(Number);

      const startDate = new Date(date);
      startDate.setHours(startHours, startMinutes, 0, 0);

      const endDate = new Date(date);
      endDate.setHours(endHours, endMinutes, 0, 0);

      return date.getTime() >= startDate.getTime() && date.getTime() <= endDate.getTime();
    },
    navigateToStudentsList(course) {
      this.updateSelectedClass(course.className);
      this.$router.push({ path: '/about' });
    }
  },
  mounted() {
    axios.get("/classInfo.json")
      .then((response) => {
        console.log("数据加载成功:", response.data);  // 添加日志
        this.courses = response.data;
        this.filterCourses();
      })
      .catch((error) => {
        console.error("获取的数据失败", error);
      });
}

};
</script>
